package org.thattoolkit.srvctl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

class SimpleCommand {
	private String cmd[];
	private String cmdPath;
	private Date execTime;
	private List<String> output;

	private ProcessBuilder pb;
	private Process p;
	private boolean started;

	public SimpleCommand(String ...p_cmd) {
		cmd = p_cmd;
		execTime = new Date();
		cmdPath = AbstractOperatingSystem.getSystem().FindCommand(cmd[0]);
		if(!cmdPath.isEmpty())
			cmd[0] = cmdPath;
		pb = new ProcessBuilder(cmd);
		started = false;
	}
	
	public boolean commandExists() {
		return !cmdPath.isEmpty();
	}
	
	public Date getExecTime() {
		return execTime;
	}

	public int getReturnCode() {
		return p.exitValue();
	}

	public List<String> getOutput() {
		return output;
	}

	public void execute() throws IOException, InterruptedException {
		if(started)
			throw new RuntimeException("Process already started");
		started = true;
		p = pb.start();
		pb.wait();
		BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while(true) {
			String line = is.readLine();
			if(line == null)
				break;
			output.add(line);
		}
	}

	public boolean isStarted() {
		return started;
	}

	static List<String> multiLineCommand(String ...cmd) {
		SimpleCommand result = simpleCommandOutput(cmd);
		return result.getOutput();
	}
	
	static String singleLineCommand(String ...cmd) {
		SimpleCommand result = simpleCommandOutput(cmd);
		if(result.getOutput().isEmpty())
			return "";
		return result.getOutput().get(0);
	}
	
	static SimpleCommand simpleCommandOutput(String ... cmd) {
		SimpleCommand result = new SimpleCommand(cmd);
		if(result.commandExists()) {
			try {
				result.execute();
			}
			catch(IOException e) {
				return result;
			}
			catch(SecurityException e) {
				return result;
			}
			catch(InterruptedException e) {
				return result;
			}
		}
		return result;
	}
}
